package com.situ.stl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.stl.dao.CoachMapper;
import com.situ.stl.dao.CourseMapper;
import com.situ.stl.entity.Coach;
import com.situ.stl.entity.Course;
import com.situ.stl.service.CoachService;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/** 
 * Service层 - 教练
 */
@Service 
public class CoachServiceImpl implements CoachService{

    /** 
     */
    @Autowired 
    private CoachMapper coachMapper;
    @Autowired
    private CourseMapper courseMapper;

    /** 
     * add
     */
    @Override 
    public int add( Coach coach) throws Exception {
        Coach sCoach = coachMapper.selectByPhone(coach.getPhone());
        if ( ! ObjectUtils.isEmpty(sCoach)) {
            throw new Exception("手机号已存在！");
        }
        int res = coachMapper.insert(coach);
        return res;
    }

    /** 
     * remove
     */
    @Override 
    public int remove( int id) throws Exception {
        // 验证ID
        Coach sCoach = coachMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sCoach)) {
            throw new Exception("教练不存在！");
        }

        // 验证课程
        List<Course> courses = courseMapper.selectByCoachId(id);
        if (!courses.isEmpty()){
            throw new Exception("当前教练有课，无法删除！");
        }

        // 删除教练
        return coachMapper.delete(id);
    }

    /** 
     * edit
     */
    @Override 
    public int edit( Coach coach) throws Exception{
        Coach sCoach = coachMapper.selectByPhone(coach.getPhone());
        if ( ! ObjectUtils.isEmpty(sCoach) && !coach.getId().equals(sCoach.getId())) {
            throw new Exception("手机号已存在！");
        }
        int res = coachMapper.update(coach);
        return res;
    }

    /** 
     * getById
     */
    @Override 
    public Coach getById( int id) {
        return coachMapper.selectByPrimaryKey(id);
    }

    /** 
     * get All
     */
    @Override 
    public List<Coach> getAll() {
        return coachMapper.selectAll();
    }

    /** 
     * search
     */
    @Override 
    public List<Coach> search( Coach coach) {
        return coachMapper.select(coach);
    }

    /** 
     * searchByPage
     */
    @Override 
    public PageInfo searchByPage( Integer page, Integer limit, Coach coach) {
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        
        PageHelper.startPage(page, limit);
        List list = coachMapper.select(coach);
        PageInfo pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

}